package pl.edu.agh.ssm.monitor.visualization;

import java.awt.event.MouseEvent;
import java.util.HashMap;

import pl.edu.agh.ssm.monitor.SessionMonitorApp;
import pl.edu.agh.ssm.monitor.data.SessionConnection;
import pl.edu.agh.ssm.monitor.data.SessionNode;
import prefuse.controls.FocusControl;
import prefuse.visual.EdgeItem;
import prefuse.visual.NodeItem;
import prefuse.visual.VisualItem;

/**
 * 
 * @author Monika Nawrot
 * 
 */

public class GraphFocusControl extends FocusControl {
	
	private HashMap<String, SessionNode> nodesMap = null;
	private HashMap<String, SessionConnection> connectionsMap = null;
	
	public GraphFocusControl(HashMap<String, SessionNode> nodesMap, 
			HashMap<String, SessionConnection> connectionsMap) {
		this.nodesMap = nodesMap;
		this.connectionsMap = connectionsMap;
	}
	
	@Override
	public void itemClicked(VisualItem visualItem, MouseEvent event) {
		
		if (event.getClickCount() != 2)
			return;
		
		if (visualItem instanceof NodeItem) {
			NodeItem node = (NodeItem) visualItem;
			String id = node.getString("id");
			/*
			 * Print id of the selected node
			 */
			System.out.println("Clicked node: " + id + ", current map size: " + nodesMap.size());
			SessionNode sessionNode = null;
			for(String key : nodesMap.keySet()) {
				if(key.equalsIgnoreCase(id)) {
					sessionNode = nodesMap.get(key);
					break;
				}
			}
			
			if(sessionNode != null) {
				GraphNodeDisplayer displayer = 
					SessionMonitorApp.getApplication().getManager().
					getNodeDisplayer(sessionNode.getNodeType());
				
				displayer.displayNodeItem(sessionNode);
			} else {
				System.out.println("Cannot find node in map");
			}
			
			
		} else if (visualItem instanceof EdgeItem) {
			EdgeItem edge = (EdgeItem) visualItem;
			String id = edge.getString("id");
			
			/*
			 * Print id of the selected edge
			 */
			System.out.println("Clicked edge: " + id);
			SessionConnection connection = null;
			
			for(String key : connectionsMap.keySet()) {
				if(key.equalsIgnoreCase(id)) {
					connection = connectionsMap.get(key);
					break;
				}
			}
			
			if(connection != null) {
				GraphEdgeDisplayer displayer = 
					SessionMonitorApp.getApplication().getManager().
					getEdgeDisplayer(connection.getMediaDesc().getMediaType());
				displayer.displayEdgeItem(connection);
			}

		}
	}
	
}
